package com.lipaluma.field.adaptor.impl;

import java.lang.reflect.Field;

import org.apache.commons.lang.StringUtils;

import com.lipaluma.annotations.adaptors.Adapt;
import com.lipaluma.annotations.adaptors.standard.Trim;
import com.lipaluma.annotations.mapping.MapColumn;
import com.lipaluma.context.Context;
import com.lipaluma.field.adaptor.Adaptor;
import com.lipaluma.xml.adaptor.XmlAdaptor;

/**
 * Adaptor use to trim the extracted value.
 * <p>
 * To initialize :
 * <ul>
 * 	<li>
 * 	<u><b>By annotations :</b></u> 3 ways are available to initialize the adaptor by annotations.<br/>
 * <ul>
 * <li>The first one : By {@link Trim} annotation.</li>
 * <li>The second one : By {@link Adapt} annotation with <code>trim</code> attribute to put at true</li>
 * <li>The last one : By {@link MapColumn} annotation with <code>trim</code> attribute to put at true</li>
 * </li>
 * </ul>
 * </li>
 * 	<li>
 * 	<u><b>By Xml :</b></u> 2 ways are available to initialize the adaptor by Xml.
 * <ul>
 * <li>
 * The first one : with the attribute trim : <br>
 * <code>&lt;ToMap field="..."   <b>trim="true"</b> ...></code><br>
 * </li>
 * <li>
 * The second one : with the element trim : <br>
 * <code>
 * &lt;ToMap field="..."  ...><br/>
 * &nbsp;&nbsp;&nbsp;<b>&lt;trim/></b><br/>
 * &lt;/ToMap>
 * </code>
 * <br>
 * </li>
 * </ul>
 * 
 * @author Mario
 */
public class TrimAdaptor implements Adaptor {

	@Override
	public boolean init(Context context, Field field) {
		boolean first = field.isAnnotationPresent(com.lipaluma.annotations.adaptors.standard.Trim.class);
		Adapt adapt = field.getAnnotation(Adapt.class);
		boolean second = adapt != null && adapt.trim();
		boolean third = context.isMappedByAnnotation() && context.getMappingManagerByAnnotation().checkTrimedOnMapping(field);
		return first || second || third;
	}
	
	@Override
	public boolean init(Context context, Field field, XmlAdaptor adaptor) {
		return true;
	}
	
	public String adapt(String value) {
		return StringUtils.trim(value.toString());
	}
}
